package com.awcall.iot.controller;


import com.awcall.iot.common.BaseController;
import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.model.*;
import com.awcall.iot.service.*;
import com.awcall.iot.utils.JsonUtils;
import com.awcall.iot.utils.RequestUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuhui
 * @since 2018-03-05
 */
@RestController
@RequestMapping("/admin/statements")
public class StatementsController extends BaseController {

    @Autowired
    private IStatementsService iStatementsService;

    @Autowired
    private IOperateLogService iOperateLogService;

    @Autowired
    private ISystemUserService iSystemUserService;

    @Autowired
    private IProjectService iProjectService;

    @Autowired
    private IBankService iBankService;

    @Autowired
    private IUserService iUserService;

    @GetMapping("/index")
    public ResponseResult index(Statements statements, Page<Statements> page) {

        EntityWrapper<Statements> statementsWarpper = getStatementsWarpper(statements);

        if (!StringUtils.isEmpty(statements.getType())) {
            statementsWarpper.eq("type", statements.getType());
        }

        iStatementsService.selectPage(page, statementsWarpper);

        return new ResponseResult<>(page);
    }

    @GetMapping("/list")
    public ResponseResult list(Statements statements) {
        EntityWrapper<Statements> statementsWarpper = getStatementsWarpper(statements);

        if (!StringUtils.isEmpty(statements.getType())) {
            statementsWarpper.eq("type", statements.getType());
        }

        List<Statements> statementsList = iStatementsService.selectList(statementsWarpper);

        return new ResponseResult<>(statementsList);
    }

    @GetMapping("/total")
    public ResponseResult total(Statements statements) {
        EntityWrapper<Statements> entityWrapper = getStatementsWarpper(statements);

        entityWrapper.in("type",new Integer[]{1,2}).setSqlSelect("ifnull(sum(price), 0)");
        Double originTotalAmount = (Double) iStatementsService.selectObj(entityWrapper);
        EntityWrapper<Statements> entityWrapper4 = getStatementsWarpper(statements);
        entityWrapper4.eq("type", 1).setSqlSelect("ifnull(sum(price), 0)");
        Double profitAmount = (Double) iStatementsService.selectObj(entityWrapper4);
        EntityWrapper<Statements> entityWrapper1 = getStatementsWarpper(statements);
        entityWrapper1.eq("type", 2).setSqlSelect("ifnull(sum(price), 0)");
        Double totalAmount = (Double) iStatementsService.selectObj(entityWrapper1);
        EntityWrapper<Statements> entityWrapper2 = getStatementsWarpper(statements);
        entityWrapper2.eq("type", 3).setSqlSelect("ifnull(sum(price), 0)");
        Double receivableAmount = (Double)iStatementsService.selectObj(entityWrapper2);
        EntityWrapper<Statements> entityWrapper3 = getStatementsWarpper(statements);
        entityWrapper3.eq("type", 4).setSqlSelect("ifnull(sum(price), 0)");
        Double handleAmount = (Double) iStatementsService.selectObj(entityWrapper3);

        ObjectNode node = JsonUtils.objectMapper.createObjectNode()
                .put("originTotalAmount", originTotalAmount)
                .put("totalAmount", totalAmount)
                .put("profitAmount", profitAmount)
                .put("receivableAmount", receivableAmount)
                .put("handleAmount", handleAmount);
        return new ResponseResult<>(node);
    }

    @GetMapping("/detail")
    public ResponseResult detail(Statements statements) {
        Statements statements1 = statements.selectById();
        if (statements1.getType() == 1 || statements1.getType() == 4){
            statements1.setPrice(-statements1.getPrice());
        }
        return new ResponseResult<>(statements1);
    }

    @PostMapping("/insert")
    public ResponseResult insert(@RequestBody Statements statements) {

        if (statements.getType() == 1 || statements.getType() == 4){
            statements.setPrice(-statements.getPrice());
        }

        if (null != statements.getBankId()){
            Bank bank = iBankService.selectById(statements.getBankId());
            statements.setBankId(bank.getId());
            statements.setBankName(bank.getName());
        }

        if (null != statements.getUserId()){
            User user = iUserService.selectById(statements.getUserId());
            statements.setUserId(user.getId());
            statements.setUserName(user.getName());
        }

        if (null != statements.getProjectId() && 0 != statements.getProjectId()){
            Project project = iProjectService.selectById(statements.getProjectId());
            statements.setProjectId(project.getId());
            statements.setProjectName(project.getName());
        }

        boolean insert = statements.insert();

        if (insert) {
            log(2, statements);
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "失败");
        }
    }

    @PostMapping("/update")
    public ResponseResult update(@RequestBody Statements statements) {

        if (statements.getType() == 1 || statements.getType() == 4){
            statements.setPrice(-statements.getPrice());
        }

        if (null != statements.getBankId()){
            Bank bank = iBankService.selectById(statements.getBankId());
            statements.setBankId(bank.getId());
            statements.setBankName(bank.getName());
        }

        if (null != statements.getUserId()){
            User user = iUserService.selectById(statements.getUserId());
            statements.setUserId(user.getId());
            statements.setUserName(user.getName());
        }

        if (null != statements.getProjectId() && 0 != statements.getProjectId()){
            Project project = iProjectService.selectById(statements.getProjectId());
            statements.setProjectId(project.getId());
            statements.setProjectName(project.getName());
        }

        boolean update = statements.updateById();

        if (update) {
            log(3, statements);
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "失败");
        }
    }

    @PostMapping("/delete")
    public ResponseResult delete(@RequestBody Statements statements) {
        Statements selectById = statements.selectById();
        boolean delete = statements.deleteById();

        if (delete) {
            log(4, selectById);
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "失败");
        }
    }

    @PostMapping("/updateType")
    public ResponseResult updateType(@RequestBody Statements statements){
        Statements statements1 = statements.selectById();
        if (statements1.getType() == 3){
            statements1.setType(2);
        }else {
            statements1.setType(1);
        }

        if (null != statements.getBankId()){
            Bank bank = iBankService.selectById(statements.getBankId());
            statements.setBankId(bank.getId());
            statements.setBankName(bank.getName());
        }

        if (null != statements.getUserId()){
            User user = iUserService.selectById(statements.getUserId());
            statements.setUserId(user.getId());
            statements.setUserName(user.getName());
        }

        if (null != statements.getProjectId() && 0 != statements.getProjectId()){
            Project project = iProjectService.selectById(statements.getProjectId());
            statements.setProjectId(project.getId());
            statements.setProjectName(project.getName());
        }

        boolean update = statements1.updateById();
        if (update) {
            log(3, statements1);
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "失败");
        }
    }

    @PostMapping("/allInsert")
    public ResponseResult allInsert(@RequestBody List<Statements> c) {
        for (Statements statements : c) {

            if (null != statements.getBankName()){
                EntityWrapper<Bank> entityWrapper = new EntityWrapper<>();
                entityWrapper.like("bank_name",statements.getBankName());
                Bank bank = iBankService.selectOne(entityWrapper);
                statements.setBankId(bank.getId());
                statements.setBankName(bank.getName());
            }

            if (null != statements.getUserName()){
                EntityWrapper<User> entityWrapper = new EntityWrapper<>();
                entityWrapper.like("bank_name",statements.getBankName());
                User user = iUserService.selectOne(entityWrapper);
                statements.setUserId(user.getId());
                statements.setUserName(user.getName());
            }

            if ("收入".equals(statements.getTypeName())) {
                statements.setType(2);
            } else if("支出".equals(statements.getTypeName())){
                statements.setType(1);
                statements.setPrice(-statements.getPrice());
            } else if("应收".equals(statements.getTypeName())){
                statements.setType(3);
            } else if("应付".equals(statements.getTypeName())){
                statements.setType(4);
                statements.setPrice(-statements.getPrice());
            }
        }
        boolean b = iStatementsService.insertBatch(c);
        if (b) {
            for (Statements statements : c) {
                log(2, statements);
            }
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "失败");
        }
    }

    /**
     * 添加log
     *
     * @param type
     * @param statements
     */
    private void log(Integer type, Statements statements) {
        SystemUser systemUser = iSystemUserService.selectById(getSystemUserId());
        OperateLog operateLog = new OperateLog();
        operateLog.setCreatedAt(new Date())
                .setSystemUserId(systemUser.getId())
                .setStatementsId(statements.getStatementsId())
                .setStatementsDescription(statements.getDescription())
                .setInformation(statements.getInformation())
                .setPrice(statements.getPrice())
                .setType(type)
                .setIp(RequestUtils.getIp())
                .setSystemUserName(systemUser.getUsername());

        if (null != statements.getBankId() && null != statements.getBankName()){
            operateLog.setBankId(statements.getBankId())
            .setBankName(statements.getBankName());
        }

        if (null != statements.getUserId() && null != statements.getUserName()){
            operateLog.setUserId(statements.getUserId())
                    .setUserName(statements.getUserName());
        }

        if (null != statements.getProjectId() && null != statements.getProjectName()){
            operateLog.setProjectId(statements.getProjectId())
                    .setProjectName(statements.getProjectName());
        }

        if (2 == type) {
            operateLog.setDescription(systemUser.getUsername() + "添加了流水");
        }

        if (3 == type) {
            operateLog.setDescription(systemUser.getUsername() + "修改了流水");
        }

        if (4 == type) {
            operateLog.setDescription(systemUser.getUsername() + "删除了流水");
        }
        iOperateLogService.insert(operateLog);
    }

    private EntityWrapper<Statements> getStatementsWarpper(Statements statements) {
        EntityWrapper<Statements> entityWrapper = new EntityWrapper<>();

        if (!StringUtils.isEmpty(statements.getStartDate())) {
            entityWrapper.gt(Statements.CREATED_AT, statements.getStartDate());
        }

        if (!StringUtils.isEmpty(statements.getEndDate())) {
            entityWrapper.lt(Statements.CREATED_AT, statements.getEndDate());
        }

        if (!StringUtils.isEmpty(statements.getBankId())) {
            entityWrapper.eq("bank_id", statements.getBankId());
        }

        if (!StringUtils.isEmpty(statements.getUserId())) {
            entityWrapper.eq("user_id", statements.getUserId());
        }

        Long systemUserId = getSystemUserId();

        SystemUser systemUser = iSystemUserService.selectById(systemUserId);

        if (null == systemUser.getProjectId() || systemUser.getProjectId()==0){
            if (!StringUtils.isEmpty(statements.getProjectId())) {
                entityWrapper.eq("project_id", statements.getProjectId());
            }
        }else {
            entityWrapper.eq("project_id", systemUser.getProjectId());
        }

        entityWrapper.orderBy(Statements.CREATED_AT, false);
        return entityWrapper;
    }

}
